package com.lzy.managersystem.controller;

import cn.hutool.core.date.DateUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lzy.managersystem.pojo.Article;
import com.lzy.managersystem.service.ArticleService;
import com.lzy.managersystem.tools.Result;
import com.lzy.managersystem.utils.TokenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/article")
public class ArticleController {

    @Autowired
    private ArticleService articleService;

    @GetMapping("/")
    public Result selectAll() {
        List<Article> list = articleService.getAllUser();
        return Result.success(list);
    }

    @PostMapping("/getById/{id}")
    public Result getArticleById(@PathVariable("id") Integer id) {
        return Result.success(articleService.getArticleById(id));
    }

    @PostMapping("/inster")
    public Result insertUser(@RequestBody Article article) {
        article.setTime(DateUtil.now());
        article.setUser(TokenUtils.getCurrentUser().getNickname());
        int flag = articleService.insterUser(article);
        return Result.success(flag);
    }

    @DeleteMapping("/{id}")
    public Result deleteUser(@PathVariable Integer id) {
        int flag = articleService.deleteUser(id);
        return Result.success(flag);
    }

    @PostMapping("/del/batch")
    public Result deleteBatchUser(@RequestBody List<Integer> ids) {
        int flag = articleService.deleteBatchUser(ids);
        return Result.success(flag);
    }

    @PutMapping("/")
    public Result UpdataUser(@RequestBody Article article) {
        article.setTime(DateUtil.now());
        article.setUser(TokenUtils.getCurrentUser().getNickname());
        int flag = articleService.updateUser(article);
        return Result.success(flag);
    }

    @GetMapping("/page")
    public Result selectUserPage(@RequestParam Integer pageSize,
                                 @RequestParam Integer pageNum,
                                 @RequestParam(defaultValue = "") String name
    ) {
        IPage<Article> articleIPage = new Page<>(pageNum, pageSize);
        QueryWrapper<Article> userQueryWrapper = new QueryWrapper<>();
        if (!name.isEmpty()) {
            userQueryWrapper.like("name", name);
        }
        return Result.success(articleService.page(articleIPage, userQueryWrapper));
    }
}
